package com.liaozhai.community.controller;

import com.liaozhai.community.annotation.LoginRequired;
import com.liaozhai.community.constant.CommunityConstant;
import com.liaozhai.community.context.BaseContext;
import com.liaozhai.community.entity.User;
import com.liaozhai.community.service.FollowService;
import com.liaozhai.community.service.LikeService;
import com.liaozhai.community.service.UserService;
import com.liaozhai.community.util.AliOssUtil;
import com.liaozhai.community.util.CommunityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    @LoginRequired
    @GetMapping("/setting")
    public String getSettingPage(){
        return "/site/setting";
    }

    @PostMapping("/upload")
    public String uploadHeader(MultipartFile headerImage, Model model){
        if(headerImage == null){
            model.addAttribute("error","您还没有选择图片");
            return "/site/setting";
        }

        try {
            //获取文件原始名
            String originalFilename = headerImage.getOriginalFilename();
            //获取随机UUID
            String uuid = CommunityUtil.generateUUID();
            //获取最后一个.的索引位置用于后续截取文件后缀名
            int index = originalFilename.lastIndexOf(".");
            //将随机UUID与截取的后缀名进行拼接成文件名
            String name = uuid + originalFilename.substring(index);
            String path = aliOssUtil.upload(headerImage.getBytes(), name);
            //上传成功
            User user = BaseContext.getUser();
            userService.updateHeader(user.getId(),path);
        } catch (IOException e) {
            log.info("文件上传失败:{}",e.getMessage());
            throw new RuntimeException("文件上传失败，服务器发生异常!",e);
        }

        return "redirect:/index";
    }


    @PostMapping("/updatepassword")
    public String updatePassword(@CookieValue ("ticket") String ticket, Model model, String originpassword, String newpassword, String confirmpassword){
        Map<String, Object> map = userService.updatePassword(originpassword, newpassword,confirmpassword);
        if(map.containsKey("originpasswordMsg")){
            model.addAttribute("originpasswordMsg", map.get("originpasswordMsg"));
            return "/site/setting";
        }
        if(map.containsKey("newpasswordMsg")){
            model.addAttribute("newpasswordMsg",map.get("newpasswordMsg"));
            return "/site/setting";
        }
        if(map.containsKey("confirmpasswordMsg")) {
            model.addAttribute("confirmpasswordMsg", map.get("confirmpasswordMsg"));
            return "/site/setting";
        }
        userService.logout(ticket);
        return "redirect:/index";
    }

    // 个人主页
    @GetMapping("/profile/{userId}")
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }

        // 用户
        model.addAttribute("user", user);
        // 点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);

        // 关注数量
        long followeeCount = followService.findFolloweeCount(userId, CommunityConstant.ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);
        // 粉丝数量
        long followerCount = followService.findFollowerCount(CommunityConstant.ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);

        // 是否已关注
        boolean hasFollowed = false;
        if (BaseContext.getUser() != null) {
            hasFollowed = followService.hasFollowed(BaseContext.getUser().getId(),CommunityConstant.ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);

        return "/site/profile";
    }
}
